package org.leafstar.shortlink.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.leafstar.shortlink.admin.common.convention.result.Result;
import org.leafstar.shortlink.admin.common.convention.result.Results;
import org.leafstar.shortlink.admin.remote.dto.LinkRemoteService;
import org.leafstar.shortlink.admin.remote.dto.req.LinkCreateReqDTO;
import org.leafstar.shortlink.admin.remote.dto.req.LinkPageReqDTO;
import org.leafstar.shortlink.admin.remote.dto.req.LinkUpdateReqDTO;
import org.leafstar.shortlink.admin.remote.dto.req.ShortLinkBatchCreateReqDTO;
import org.leafstar.shortlink.admin.remote.dto.resp.LinkCreateRespDTO;
import org.leafstar.shortlink.admin.remote.dto.resp.LinkPageRespDTO;
import org.leafstar.shortlink.admin.remote.dto.resp.ShortLinkBaseInfoRespDTO;
import org.leafstar.shortlink.admin.remote.dto.resp.ShortLinkBatchCreateRespDTO;
import org.leafstar.shortlink.admin.util.EasyExcelWebUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 远程调用的接口层
 */
@RestController
@RequestMapping("/api/short-link/admin/v1")
public class ShortLinkController {
    /**
     * 批量创建短链接
     */
    @SneakyThrows
    @PostMapping("/create/batch")
    public void batchCreateShortLink(@RequestBody ShortLinkBatchCreateReqDTO requestParam, HttpServletResponse response) {
        Result<ShortLinkBatchCreateRespDTO> shortLinkBatchCreateRespDTOResult = LinkRemoteService.batchCreateShortLink(requestParam);
        if (shortLinkBatchCreateRespDTOResult.isSuccess()) {
            List<ShortLinkBaseInfoRespDTO> baseLinkInfos = shortLinkBatchCreateRespDTOResult.getData().getBaseLinkInfos();
            EasyExcelWebUtil.write(response, "批量创建短链接-SaaS短链接系统", ShortLinkBaseInfoRespDTO.class, baseLinkInfos);
        }
    }

    /**
     * 创建短链接
     * @param requestParam LinkCreateReqDTO
     * @return 创建的结果，比如gid,originLink,fullShortLink等
     */
    @PostMapping("/create")
    public Result<LinkCreateRespDTO> createShortLink(@RequestBody LinkCreateReqDTO requestParam) {
        return LinkRemoteService.createShortLink(requestParam);
    }

    /**
     * 分页查询短链接
     * @param requestParam 带有分页的参数，需要gid,size,current
     * @return page集合
     */
    @GetMapping("/page")
    public Result<IPage<LinkPageRespDTO>> pageShortLink(LinkPageReqDTO requestParam) {
        return LinkRemoteService.pageShortLink(requestParam);
    }

    /**
     * 更新短链接
     * @param requestParam 请求更新实体
     * @return 更新结果
     */
    @PostMapping("/update")
    public Result<Void> updateShortLink(@RequestBody LinkUpdateReqDTO requestParam) {
        LinkRemoteService.updateShortLink(requestParam);
        return Results.success();
    }

}
